package com.gla.service;

import com.gla.dao.ShoppingCartMapper;
import com.gla.domain.Shop;
import com.gla.domain.ShoppingCartItem;
import com.gla.result.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class ShoppingCartService {
    @Resource
    ShoppingCartMapper shoppingCartMapper;

    public List<ShoppingCartItem> select(HashMap<String,Object> map){
        return shoppingCartMapper.select(map);
    }

    public List<ShoppingCartItem> selectByUserId(Integer id){
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("user_id",id);
        return shoppingCartMapper.select(map);
    }

    public Result insert(Integer commodity_id, Integer user_id,Integer number){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("commodity_id",commodity_id);
        map.put("user_id",user_id);
        List<ShoppingCartItem> list =  shoppingCartMapper.select(map);
        //购物车不存在该记录,插入
        if(list.size()==0){
            //插入购物车记录
            shoppingCartMapper.insert(commodity_id,user_id,number);
            return Result.succeed("购物车新增成功");
        }
        //存在，数量+1
        else{
            updateNumber(list.get(0).getId(),number);
            return Result.succeed("原记录存在，数量加，变为"+(list.get(0).getNumber()+number));
        }
    }

    public Result delete(Integer id){
        shoppingCartMapper.delete(id);
        return Result.succeed("删除成功");
    }

    public void updateNumber(Integer id, Integer n) {
        //根据id获取购物车数据
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("id",id);
        ShoppingCartItem carBook = shoppingCartMapper.select(map).get(0);
        Integer oldNum = carBook.getNumber();//获取原数量
        //修改数量n
        if(oldNum+n > 0){
            shoppingCartMapper.updateNumber(id,oldNum+n);
        }
        //数量为0，删除
        else if(oldNum+n == 0){
            delete(id);
        }
    }

    public Shop selectShop(Integer shop_id) {
        return shoppingCartMapper.selectShop(shop_id);
    }
}
